/*
 * Copyright 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ofek.eventos;

import java.text.Bidi;
import java.util.ArrayList;
import java.util.Calendar;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import com.ofek.applicationbase.utils.Log;
import com.ofek.applicationbase.utils.ReflectionUtils;
import com.ofek.eventos.EventsFragment.EventsFragmentController;
import com.ofek.eventos.ToolController.ToolListener;
import com.ofek.eventos.db.ContextWrapper;
import com.ofek.eventos.db.EventosDatabaseService;
import com.ofek.eventos.db.PageWrapper;
import com.ofek.eventos.util.TimeUtils;

public class PageActivity extends EventsFragmentActivity implements EventsFragmentController, ToolListener {
	public interface EditListener {
		public void onEditChecked(boolean b);
	}

	public static final String CONTEXT_DEFINER = "DiaryActivity.CONTEXT_DEFINER";

	private ViewPager mPager;
	private DiaryAdapter mPagerAdapter;
	private boolean leftToRight;
	public PageFragment currentFragment;
	public Calendar todayShowing;
	private ArrayList<PageWrapper> pagesProps;
	private PageWrapper currentPageDefiner;
	private boolean edit;

	private ToolController toolController;

	private ContextWrapper contextDefiner;

	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		final MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.page_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		if ( item.getItemId()==R.id.action_edit ) 
			EventosAndroidUtils.startFormActivity(this,FormActivity.ACTION_FORM_PAGE,currentPageDefiner);
		if ( item.getItemId()==R.id.action_add ) 
			EventosAndroidUtils.startFormActivity(this,FormActivity.ACTION_FORM_PAGE,contextDefiner);
		if ( item.getItemId()==R.id.action_delete ) {
			contextDefiner.remove(currentPageDefiner);
			mPagerAdapter.notifyDataSetChanged();
			if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
				recreate();
			} else {
				finish();
				startActivity(getIntent());
			}
		}
		return true;
	}
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("onCreate");
		setContentView(R.layout.activity_diary);
		contextDefiner = (ContextWrapper) getIntent().getSerializableExtra(CONTEXT_DEFINER);
		pagesProps = contextDefiner.getAll();
		mPager = (ViewPager) findViewById(R.id.view_flipper);
		final Bidi bidi = new Bidi(getString(R.string.today), Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
		leftToRight = bidi.baseIsLeftToRight();

		mPagerAdapter = new DiaryAdapter(getSupportFragmentManager());
		mPager.setAdapter(mPagerAdapter);
		toolController = new ToolController((ViewGroup) findViewById(R.id.toolView));
		toolController.registerToolListener(this);
		toolController.setIcon(android.R.drawable.ic_menu_today);

		mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

			@Override
			public void onPageSelected(final int i) {
				updatePage(i);
			}

		});

		int i=-1;
		if (!leftToRight) 
			i=pagesProps.size()-1;
		else if ( pagesProps.size()>0 )  
			i=0;

		if ( i >= 0 ) {
			try {
				ReflectionUtils.setValue(mPager, "mCurItem",-1);
			} catch (final Exception e) {
				e.printStackTrace();
			}
			mPager.setCurrentItem(i);
		}
		mPagerAdapter.onCreate(savedInstanceState);
	}

	/**
	 * 
	 */
	private void updatePage(final int i) {
		currentPageDefiner = leftToRight ? pagesProps.get(i) : pagesProps.get(pagesProps.size()-i-1);
		toolController.setHeader(currentPageDefiner.getPageTitle(PageActivity.this));
		if (currentPageDefiner.getPageSubTitle(PageActivity.this)!=null) 
			toolController.setSubHeader(currentPageDefiner.getPageSubTitle(PageActivity.this));
		else 
			toolController.setSubHeader(null);
	}

	static class DairyFragmentData {

		int res;
		long start,end;
		String subTitle;

		public DairyFragmentData(final int res, final long start, final long end, final String subTitle) {
			super();
			this.res = res;
			this.start = start;
			this.end = end;
			this.subTitle=subTitle;
		}

	}
	public boolean getEditState() {
		return edit;
	}
	@Override
	protected void onResume() {
		super.onResume();
		final Calendar today = Calendar.getInstance();
		today.set(Calendar.HOUR_OF_DAY, 0);
		today.set(Calendar.MINUTE, 0);
		today.set(Calendar.SECOND, 0);
		today.set(Calendar.MILLISECOND, 0);
		if (today.compareTo(TimeUtils.getTodayCal())!=0) {
			mPagerAdapter = new DiaryAdapter(getSupportFragmentManager());
			mPager.setAdapter(mPagerAdapter);
		}
		pagesProps = contextDefiner.getAll();
		if ( pagesProps.isEmpty() ) {
			final View noPages = findViewById(R.id.no_pages);
			noPages.setVisibility(View.VISIBLE);
			noPages.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(final View v) {
					EventosAndroidUtils.startFormActivity(PageActivity.this, FormActivity.ACTION_FORM_PAGE, contextDefiner);
				}
			});
			mPager.setVisibility(View.GONE);
			return;
		} else {
			final View noPages = findViewById(R.id.no_pages);
			mPager.setVisibility(View.VISIBLE);
			noPages.setVisibility(View.GONE);
		}
		try {
			final int i = (Integer) ReflectionUtils.getValue(mPager, "mCurItem");
			ReflectionUtils.setValue(mPager, "mCurItem",-1);
			mPager.setCurrentItem(i);
		} catch (final Exception e) {
			e.printStackTrace();
		}

		mPagerAdapter.onResume();

	}

	@Override
	protected void onPause() {
		super.onPause();
		mPagerAdapter.onPause();
	}
	@Override
	public void onBackPressed() {
		stopService(new Intent(this,EventosDatabaseService.class));
		super.onBackPressed();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mPagerAdapter.onDestroy();
	}

	public class DiaryAdapter extends FragmentPagerAdapter {





		//		private final BroadcastReceiver dataSetChangedReciever = new BroadcastReceiver() {
		//
		//			@Override
		//			public void onReceive(final Context context, final Intent intent) {
		//				notifyDataSetChanged();
		//			}
		//		};
		public DiaryAdapter(final FragmentManager fragmentManager) {
			super(fragmentManager);
		}

		@Override
		public Fragment getItem(final int i) {
			return leftToRight ? PageFragment.newInstance(pagesProps.get(i)) : PageFragment.newInstance(pagesProps.get(pagesProps.size()-i-1));
		}
		@Override
		public int getCount() {
			return pagesProps.size();
		}

		@Override
		public void setPrimaryItem(final ViewGroup container, final int position,
				final Object object) {
			currentFragment = (PageFragment) object;
			super.setPrimaryItem(container, position, object);
		}
		public void onCreate(final Bundle state) {
			//LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(dataSetChangedReciever , new IntentFilter(Constants.EVENT_NOTIFY_PAGE_SET_CHANGED));
		}
		public void onResume() {
			notifyDataSetChanged();
		}
		public void onPause() {

		}
		public void onDestroy() {
			//LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(dataSetChangedReciever);
		}

	}
	@Override
	public void onShowing(final Fragment frag) {
		if (currentFragment==null) 
			currentFragment = (PageFragment) frag;
	}

	@Override
	public void onEditChecked(final boolean b) {
		edit = b;
		if (currentFragment!=null) 
			currentFragment.setEdit(edit);
	}
	@Override
	public void onSearchClicked() {
		final Intent intent = new Intent(this, SearchActivity.class);
		intent.putExtra(SearchActivity.INTENT_KEY_SEARCH_DEFAULTS, currentPageDefiner);
		startActivity(intent);
	}

	@Override
	public void onAddClicked() {
		EventosAndroidUtils.startFormActivity(this, FormActivity.ACTION_FORM_EVENT, currentPageDefiner);
	}


}
